from matplotlib import rcParams
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from scipy.stats import norm
import matplotlib.ticker as ticker
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates

import matplotlib.gridspec as gridspec



rcParams['font.sans-serif'] = ['SimHei']  # 中文为宋体
rcParams['font.serif'] = ['Times New Roman']  # 英文为新罗马
rcParams['axes.unicode_minus'] = False  # 正常显示负号
rcParams['font.size'] = 15  # 设置字号
#########################################################################################
#在最大的子图中，我们通过散点图，绘制了联合分布情况，
# 而两个小的子图，通过频次直方图绘制了边缘分布。这种图在统计分析上非常有用。

plt.style.use('seaborn-notebook')



data=pd.read_csv('E:\江苏移动-hzy工作资料\\5GC学习资料\\01-中兴5GC资料\python-tasks\show interface brief.csv')

df = data.loc[:, ['run_time', 'BW(Mbps)','host_ip']]
df.columns = ['time', 'data','host_ip']

df['data']=df['data']+range(0,len(df['data']))
start_date = pd.to_datetime('2022-01-01 01:00:00')
end_date = pd.to_datetime('2022-12-31')

# date_list = pd.date_range(start_date, end_date, freq='D').strftime('%Y-%m-%d').tolist()
date_list = pd.date_range(start=start_date, periods=len(df), freq='Min').strftime('%Y-%m-%d %H:%M:%S').tolist()
df['time']=pd.to_datetime(date_list)

#########################################################################################
# mean = [0, 0]
# cov = [[1, 1], [1, 4]]
# x, y = np.random.multivariate_normal(mean, cov, 3000).T

host_ip_list=df['host_ip'].unique()
x1=df[df['host_ip']==host_ip_list[0]]['time']
x2=df[df['host_ip']==host_ip_list[1]]['time']

y1=df[df['host_ip']==host_ip_list[0]]['data']
y2=df[df['host_ip']==host_ip_list[1]]['data']

#########################################################################################

plt.figure(figsize=(14,6),constrained_layout=True)
grid = plt.GridSpec(4, 4, wspace=0.5, hspace=0.5)

# grid = gridspec(4, 4, wspace=0.5, hspace=0.5)

ax_main = plt.subplot(grid[0:3,1:4])
# plt.plot(x,y,'ok',markersize=3,alpha=0.24,color='red')
#plt.plot('ok') 会绘制一个黑色圆圈，'ok' 表示黑色（'k'）圆圈（'o'）。
ax_main.scatter(x1,y1, alpha=.9, marker='o',s=12, c='b',label=host_ip_list[0]+':数据集')
# ax_main.scatter(x1,y2, alpha=.9, marker='*',s=12, c='r',label=host_ip_list[1]+':数据集')


ax_main.legend(prop={'size': 12})
ax_main.set_xlabel('时间',fontweight='bold',fontsize=14) # 设置横纵轴label,加粗
# ax_main.set_ylabel('流量(Mbps)',fontweight='bold',fontsize=14)

# 设置主刻度格式
hoursLoc = mdates.HourLocator(interval=1)  # 为1小时为1主刻度
# 设置副刻度格式
minute1 =  mdates.MinuteLocator(interval=1)
minute3 =  mdates.MinuteLocator(interval=3)

# minute = mdates.MinuteLocator(byminute=[0, 10, 20, 30, 40, 50])
ax_main.xaxis.set_major_locator(minute3)
ax_main.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M\n%Y-%m-%d'))

ax_main.xaxis.set_minor_locator(minute1) # 设置x轴刻度，每10分钟显示一个
# ax_main.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))


# plt.setp(ax_main.xaxis.get_majorticklabels(), rotation=90)
# 设置主刻度旋转角度和刻度label刻度间的距离pad
ax_main.tick_params(which='major', axis='x', length=5, pad=4, direction='in',labelsize=11)
ax_main.tick_params(which='minor', axis='x', direction='in', labelsize=10.5)
ax_main.tick_params(axis='y', direction='in', labelsize=12)

ax_main.xaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
ax_main.xaxis.grid(True, which='minor',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
ax_main.yaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层


#########################################################################################
#########################################################################################
y_hist = plt.subplot(grid[0:3,0],xticklabels=[],sharey=ax_main)#和大子图共y轴
y_hist.hist(y1,60, density=True,orientation='horizontal',alpha=0.8, color='b',edgecolor='black',zorder=10)#图形水平绘制
#bins：这个参数指定bin(箱子)的个数,也就是总共有几条条状图
#density=True，归一化，密度，可以与kde的图单位一致

# 根据示例数据拟合正态分布曲线
mu, std = norm.fit(y1)
x11 = np.linspace(y1.min(), y1.max())
y11 = norm.pdf(x11, mu, std)
y_hist.plot(y11, x11, 'r--', lw=1,zorder=10)

# sns.kdeplot(y, ax=y_hist,kernel='gau', color="g", alpha=.7)#需要旋转，

# 添加网格线，并自定义样式
#主次刻度
yminorLocator = MultipleLocator(1)             # 将此y轴次刻度标签设置为，以1为间隔
xmajorLocator = MultipleLocator(0.02)            # 将此x轴次刻度标签设置为，以1为间隔
# xminorLocator = MultipleLocator(0.05)            # 将此x轴次刻度标签设置为，以1为间隔
y_hist.set_xlim([0, 0.12])

y_hist.yaxis.set_minor_locator(yminorLocator)

# y_hist.xaxis.set_minor_locator(xminorLocator)
# y_hist.xaxis.set_minor_formatter(ticker.PercentFormatter(xmax=1,decimals=0)) # 设置次刻度为百分比
y_hist.xaxis.set_major_locator(xmajorLocator)
y_hist.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=1,decimals=0)) # 设置次刻度为百分比

y_hist.xaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
# y_hist.xaxis.grid(True, which='minor',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
y_hist.yaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层


# 旋转主刻度标签90度
plt.setp(y_hist.xaxis.get_majorticklabels(), rotation=90)


y_hist.set(xlabel='',ylabel='流量(Mbps)') # 设置横纵轴标签与图像标题
y_hist.invert_xaxis()#y轴调换方向





#########################################################################################
#########################################################################################
#
# x_hist = plt.subplot(grid[3,1:4],yticklabels=[],sharex=ax_main)#和大子图共x轴
# x_hist.hist(x1,60,density=True,orientation='vertical',color='b',edgecolor='black')#图形垂直绘制
# # 根据示例数据拟合正态分布曲线
# mu, std = norm.fit(x1)
# x22 = np.linspace(x1.min(), x1.max())
# y22 = norm.pdf(x22, mu, std)
# x_hist.plot(x22, y22, 'r--', lw=1)
#
#
#
#
# # 添加网格线，并自定义样式
# #主次刻度
# yminorLocator = MultipleLocator(0.1)             # 将此y轴次刻度标签设置为，以1为间隔
# xmajorLocator = MultipleLocator(1)            # 将此x轴次刻度标签设置为，以1为间隔
# # xminorLocator = MultipleLocator(0.05)            # 将此x轴次刻度标签设置为，以1为间隔
#
#
# x_hist.xaxis.set_minor_locator(xmajorLocator)
#
# x_hist.yaxis.set_major_locator(yminorLocator)
# x_hist.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1,decimals=0)) # 设置次刻度为百分比
#
# x_hist.xaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
# x_hist.yaxis.grid(True, which='major',linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层
#
#
# # 旋转主刻度标签90度
# # plt.setp(x_hist.yaxis.get_majorticklabels(), rotation=90)
#
#
# x_hist.set(xlabel='x轴标题',ylabel='y轴标题') # 设置横纵轴标签与图像标题
#
# x_hist.invert_yaxis()#y轴调换方向
plt.show()
